<?php

namespace App\Http\Controllers;

use App\Models\Coupons;
use App\Models\Member;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CouponController extends Controller
{
    /**
     * 获取用户创建的卡券列表
     */
    public function index(Request $request)
    {
        $_limit = $request->limit;
        $_type = $request->input('type', 'qb');
        $Coupon = Coupons::where('member_id',auth('member')->id())
            ->offset($_limit[0])
            ->limit($_limit[1])
            ->orderByRaw('status = 2 DESC')
            ->orderBy('id','desc');
        if($_type != 'qb') {
            $Coupon->where("type", $_type);
        }
        $Coupon = $Coupon->get();
        return response(['data'=>$Coupon]);
    }

    /**
     * 新增或者修改卡券
     */
    public function edit($_id = '',Request $request)
    {
        $_coupon_check = Setting::value('coupon_check');
        $_member_id = auth('member')->id();
        if($_id) {
            $_data = $request->input();
            if(isset($_data['cover'])) {
                $_data['cover'] = $_data['cover'][0];
            } else {
                $_data['cover'] = 0;
            }
            if($_coupon_check){
                $_data['status'] = 2;
                $this->sendCheckNotice('coupon',$_member_id);
            }
            Coupons::where('id',$_id)->update($_data);
        } else {
            $Coupon = Coupons::create([
                'member_id' => $_member_id,
                'name' => $request->name,
                'address' => $request->address,
                'cover' => $request->cover,
                'type' => $request->type,
                'type_value' => $request->type_value,
                'time_type' => $request->time_type,
                'time' => $request->time ? $request->time : 0,
                'detail' => $request->detail,
                'status' => $_coupon_check == 1 ? 2 : 1
            ]);
            $_id = $Coupon->id;
            if($Coupon->status == 2) {
                $this->sendCheckNotice('coupon',$_member_id);
            }
        }
        return response(['data'=>$_id]);
    }

    /**
     * 获取一个卡券详情
     */
    public function show($_id, Request $request)
    {
        $Coupon = Coupons::find($_id);
        if($Coupon) {
            $_coupon = $Coupon->toArray();
            if($request->original) {
                $_coupon['cover'] = DB::table('coupons')
                    ->where('id',$_id)
                    ->value('cover');
            }
            $_response = response(['data'=>$_coupon]);
        } else {
            $_response = response(['message'=>'请求数据不存在'], 410);
        }
        return $_response;
    }

    /**
     * 删除卡券
     */
    public function destroy($_id)
    {
        if(Coupons::destroy($_id)) {
            $_response = response(['data'=>'success']);
        } else {
            $_response = response(['message'=>'删除失败'], 402);
        }
        return $_response;
    }

    //-----------------------------------------------------

    /**
     * 等待审核卡券的总数
     */
    public function checkTotal()
    {
        return response(["data"=>Coupons::where("status",2)->count()]);
    }

    /**
     * 获取审核列表
     */
    public function checkList(Request $request)
    {
        $_limit = $request->input('limit',[0,10]);
        $Coupon = Coupons::where("status",2)
            ->offset($_limit[0])
            ->limit($_limit[1])
            ->orderBy("updated_at","desc")
            ->get();
        if($Coupon) {
            foreach($Coupon as $item) {
                $item->member;
            }
        }
        return response(["data"=>$Coupon]);
    }

    /**
     * 卡券通过审核
     * @param $id
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function pass($id)
    {
        $Coupon = Coupons::find($id);
        $Coupon->status = 1;
        if($Coupon->save()) {
            if(!$this->sendTplMessage($Coupon->member_id,true,'卡券审核通过')) {
                $this->sendSubscribeMessage($Coupon->member_id,true,'卡券审核通过');
            }
            $_response = response(['data'=>'success']);
        } else {
            $_response = response(['message'=>'操作失败']);
        }
        return $_response;
    }

    /**
     * 卡券审核失败
     * @param $id
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function refuse($id,Request $request)
    {
        $_remark = $request->remark;
        $Coupon = Coupons::find($id);
        $Coupon->status = 3;
        if($Coupon->save()) {
            if(!$this->sendTplMessage($Coupon->member_id,false,$_remark)) {
                $this->sendSubscribeMessage($Coupon->member_id,false,$_remark);
            }
            $_response = response(['data'=>'success']);
        } else {
            $_response = response(['message'=>'操作失败']);
        }
        return $_response;
    }

    /**
     * 拒绝审核卡券，并且删除卡券
     * @param $id
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function remove($id,Request $request)
    {
        $_remark = $request->remark;
        $Coupon = Coupons::find($id);
        if(Coupons::destroy($id)) {
            if(!$this->sendTplMessage($Coupon->member_id,false,$_remark)) {
                $this->sendSubscribeMessage($Coupon->member_id,false,$_remark);
            }
            $_response = response(['data'=>'success']);
        } else {
            $_response = response(['message'=>'操作失败']);
        }
        return $_response;
    }

    /**
     * 发送模板消息
     * @param int $_member_id 会员id
     * @param boolean $_is_pass 是否通过审核
     * @param string $_remark 备注信息
     * @return array|bool|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    private function sendTplMessage($_member_id,$_is_pass,$_remark)
    {
        $Setting = $this->getConfig();
        if(empty($Setting->message->result_check_tpl)) return false;
        $Wechat = $this->wechat();
        $_result = $Wechat->template_message->send([
            'touser' => Member::where("id",$_member_id)->value('openid'),
            'template_id' => $Setting->message->result_check_tpl,
            'url' => route('app'),
            'data' => [
                'first' => [
                    'value' => $Setting->website_name.'-卡券审核通知'
                ],
                'keyword1' => [
                    'value' => '管理员'
                ],
                'keyword2' => [
                    'value' => $_is_pass ? '审核通过' : '审核未通过'
                ],
                'keyword3' => [
                    'value' => date('Y-m-d H:i:s')
                ],
                'remark' => [
                    'value' => $_remark
                ]
            ]
        ]);
        if($_result['errcode'] == 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 发送订阅消息
     * @param $_member_id
     * @param $_is_pass
     * @param $_remark
     * @return array|bool|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    private function sendSubscribeMessage($_member_id,$_is_pass,$_remark)
    {
        $Setting = $this->getConfig();
        if(empty($Setting->message->result_check_sub)) return false;
        $_data = array(
            "thing10" => array(
                "value" => $Setting->website_name."-卡券审核结果"
            ),
            "phrase8" => array(
                "value" => $_is_pass ? "审核通过" : "审核未通过"
            ),
            "thing4" => array(
                "value" => $_remark
            ),
            "time9" => array(
                "value" => date("Y-m-d H:i:s")
            )
        );
        return $this->sendSubscribe(
            $_member_id,
            $Setting->message->result_check_sub,
            $_data,
            route('app')
        );
    }
}
